package com.lms.web;

import com.lms.mapper.AdminDAO;
import com.lms.pojo.Admin;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取请求参数:用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        验证用户名和密码:调用业务方法
        boolean isLogin = verifyUser(username, password);
        if (isLogin) {
//        登录成功:设置Cookie或者Session,跳转界面
            //设置Session
            HttpSession session = req.getSession();
            session.setAttribute("username", username);
            session.setAttribute("password", password);
            //TODO  跳转界面
            resp.sendRedirect("index.jsp");
//            req.getRequestDispatcher("/Book_information").forward(req, resp);
        } else {
//        登录失败:提示信息,跳回登录页
            resp.sendRedirect("login.jsp");
            resp.getWriter().print("登录失败");
        }
    }


    //验证账号
    private boolean verifyUser(String username, String password) {
        if (username != null && password != null) {
            Admin admin = new Admin();
            admin.setAdminName(username);
            admin.setAdminPassword(password);
            AdminDAO adminDAO = new AdminDAO();
            return adminDAO.login(admin);
        }
        return false;
    }
}
